﻿using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace Mengsk.ProxyDelivery.Exporter
{
    public class XlsExportFile : IExportFile
    {

        private HSSFWorkbook workbook = null;
        private ISheet sheet = null;

        public override void Open()
        {
            if (this.ExportInfo == null)
            {
                throw new ArgumentNullException("ExportInfo");
            }

            if (this.workbook != null)
            {
                throw new Exception("文档已经打开");
            }

            this.workbook = new HSSFWorkbook();
            this.sheet=this.workbook.CreateSheet(this.ExportInfo.SheetName);
            this.IsOpened = true;
        }

        public override void WriteData(ExportData[] datas)
        {
            if (this.sheet == null)
            {
                throw new InvalidOperationException("文档未打开不能写入");
            }
            var row = this.sheet.CreateRow(this.sheet.PhysicalNumberOfRows);
            foreach (var data in datas)
            {
                var cell = row.CreateCell(row.Cells.Count, NPOI.SS.UserModel.CellType.String);
                cell.SetCellValue(data.Value);
            }
        }

        public override void Close()
        {
            if (this.sheet == null)
            {
                throw new InvalidOperationException("文档未打开不能关闭");
            }

            using (FileStream fs = new FileStream(this.ExportInfo.FilePath, FileMode.Create))
            {
                this.workbook.Write(fs);
            }
            this.sheet = null;
            this.workbook = null;
            this.IsOpened = false;
        }
    }
}
